<?php

namespace model;

/**
 * Description of TblRelatedProduct
 *
 * @author Damian
 */
class TblRelatedProduct extends Model{
    
    /**
     *@column
     * @primary
     * @type int
     * @readwrite
     */
    public $RelatedProductID;
    const ID="RelatedProductID";
    
    /**
    *
    * @readwrite
    */
    public $Product1;
    const PRODUCT_1="Product1";
    
     /**
    *
    * @readwrite
    */
    public $Product2;
    const PRODUCT_2="Product2";
    /**
     * @readwrite
     */
    public $ShopID;
    const SHOP_ID="ShopID";
    
    /**
     * <p>znajduje produkty powiazane</p>
     * @param type $productID <p>do tego produktu szukamy powiązanych</p>
     * @param type $shopID <p>sklep w którym szukamy</p>
     * @return \model\DataTable <p>jeśli produkty znalezione, jeśli nie zwraca false</p>
     */
    public static function findRelatedProducts($productID,$shopID){
        $relatedCriteria = new \model\Criteria();
            $relatedCriteria->from(\model\TblRelatedProduct::getModel()->getTable())
                    ->where(\model\TblRelatedProduct::PRODUCT_1, "=", $productID)
                    ->where(\model\TblRelatedProduct::PRODUCT_2, "=", $productID, false, " or ")
                    ->where(TblRelatedProduct::SHOP_ID, "=", $shopID,false, " and ");
            $relatedIDs = array();
            foreach ($relatedCriteria->all() as $relation) {
                if ($relation["tblrelatedproduct"]["Product1"] == $productID) {
                    $relatedIDs[] = $relation["tblrelatedproduct"]["Product2"];
                }
                if ($relation["tblrelatedproduct"]["Product2"] == $productID) {
                    $relatedIDs[] = $relation["tblrelatedproduct"]["Product1"];
                }
            }
            if (sizeof($relatedIDs) > 0) {
                $relatedProductsCriteria = new \model\Criteria();
                $relatedProductsCriteria->from(\model\TblProduct::getModel()->getTable())
                        ->in(\model\TblProduct::ID, $relatedIDs);
                $relatedProdutcs = new \model\DataTable(\model\TblProduct::getModel()->all($relatedProductsCriteria), true);
                return $relatedProdutcs;
            }
            return false;            
    }
}
